import React from 'react';
import PropTypes from 'prop-types';
import DataSet from '@antv/data-set';
import {partOrderList} from '../Enum';
import {Spin, Card, Row, Col} from 'antd';
import {injectIntl, formatMessage} from './intl';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {Chart, Geom, Axis, Tooltip, Legend, Label, View} from 'bizcharts';
export class TablePanel extends React.PureComponent {
    // eslint-disable-next-line react/sort-comp
    onClickLegend = (ev, legendItems, box) => {
        setTimeout(() => {
            const checked = ev.checked;
            const value = ev.item.value;
            if(value === box)
                if(checked) {
                    this.chart.get('views')[0].get('geoms')[0].show();
                } else {
                    this.chart.get('views')[0].get('geoms')[0].hide();
                }
            const newLegend = legendItems.map(d => {
                if(d.value === value)
                    return Object.assign({}, d, {
                        checked,
                    });
                return d;
            });
            this.chart.filter('type', t => {
                const legendCfg = newLegend.find(i => i.value === t);
                return legendCfg && legendCfg.checked;
            });
            
            this.chart.legend({
                items: newLegend
            });
            this.chart.repaint();
        }, 0);
    }
    chartsContent = (dvRate, scale, legendItems, arr, name, val, box) =>
        (<Chart forceFit data={dvRate} scale={scale}
            style={{fontSize: '12'}}
            height={400}
            padding={['5%', '6%', '18%']}
            onGetG2Instance={c => {
                this.chart = c;
            }}>
            <Legend
                custom
                allowAllCanceled
                items={legendItems}
                onClick={ev => this.onClickLegend(ev, legendItems, box)} />
            <Axis name="month" />
            <Axis name="value" position={'left'} />
            <Tooltip />
            <Geom
                type="interval"
                position="month*value"
                color={['type', value => {
                    if(value === name)
                        return '#4F81BD';
                    if(value === val)
                        return '#C0504D';
                }]}
                adjust={[{
                    type: 'dodge',
                    marginRatio: 1 / 1.5,
                }]}>
                <Label
                    content="value"
                    textStyle={{
                        textBaseline: 'top',
                        fill: '#404040',
                        fontSize: '12',
                    }}/>
            </Geom>
            <View data={arr} >
                <Axis name={box} position="right" />
                <Geom type="line" position={`month*${box}`} color="#98B954" size={3} >
                    <Label
                        content={box}
                        textStyle={{
                            textBaseline: 'top',
                            fill: '#404040',
                            fontSize: '12',
                        }}/>
                </Geom>
            </View>
        </Chart>);
    render() {
        const {data: {varietyData = [], amountMeetData = [], quantityData = []}, conditions} = this.props;
        // eslint-disable-next-line no-nested-ternary
        const arr = conditions.type === partOrderList.品种满足率 ? varietyData.map(v => ({
            month: v.month,
            PI项数: v.variety,
            备货项数: v.deliveryVariety,
            品种满足率: v.rate
        })) : conditions.type === partOrderList.金额满足率 ? amountMeetData.map(v => ({
            month: v.month,
            PI金额: v.variety,
            备货金额: v.deliveryVariety,
            金额满足率: v.rate
        })) : quantityData.map(v => ({
            month: v.month,
            PI数量: v.variety,
            备货数量: v.deliveryVariety,
            数量满足率: v.rate
        }));
        //柱状图与折线图
        const dsRate = new DataSet();
        dsRate.setState('type', '');
        const dvRate = dsRate.createView().source(arr);
        
        dvRate.transform({
            type: 'fold',
            // eslint-disable-next-line no-nested-ternary
            fields: conditions.type === partOrderList.品种满足率
                ? ['PI项数', '备货项数']
                : conditions.type === partOrderList.金额满足率
                    ? ['PI金额', '备货金额']
                    : ['PI数量', '备货数量'],
            key: 'type', // key字段
            value: 'value', // value字段
        })
            .transform({
                type: 'filter',
                callback: d => d.type !== dsRate.state.type
            });
        const val = {
            type: 'linear',
            formatter: val => `${val.toFixed(2)}%`,
            tickCount: 10,
        };
        // eslint-disable-next-line no-nested-ternary
        const scale = conditions.type === partOrderList.品种满足率
            ? {
                品种满足率: val,
                value: {
                    alias: '品种\n满\n足\n率'
                }
            } : conditions.type === partOrderList.金额满足率
                ? {
                    金额满足率: val,
                    value: {
                        alias: '金额\n满\n足\n率'
                    }
                } : {
                    数量满足率: val,
                    value: {
                        alias: '数量\n满\n足\n率'
                    }
                };
        
        const legendItems = [
            {
                // eslint-disable-next-line no-nested-ternary
                value: conditions.type === partOrderList.品种满足率
                    ? 'PI项数'
                    : conditions.type === partOrderList.金额满足率
                        ? 'PI金额'
                        : 'PI数量',
                marker: {
                    symbol: 'square',
                    fill: '#3182bd',
                    radius: 5
                }
            },
            {
                // eslint-disable-next-line no-nested-ternary
                value: conditions.type === partOrderList.品种满足率
                    ? '备货项数'
                    : conditions.type === partOrderList.金额满足率
                        ? '备货金额'
                        : '备货数量',
                marker: {
                    symbol: 'square',
                    fill: '#C0504D',
                    radius: 5
                }
            },
            {
                // eslint-disable-next-line no-nested-ternary
                value: conditions.type === partOrderList.品种满足率
                    ? '品种满足率'
                    : conditions.type === partOrderList.金额满足率
                        ? '金额满足率'
                        : '数量满足率',
                marker: {
                    symbol: 'hyphen',
                    stroke: '#98B954',
                    radius: 5,
                    lineWidth: 3
                },
                checked: true
            },
        ];
        return (
            <div>
                <Spin spinning={this.props.loading}>
                    <Card>
                        {conditions.type === partOrderList.品种满足率 &&
                            <DescriptionList size="large" title={<Row><Col span={12}>
                                {formatMessage({
                                    id: 'detailPanel.table.varietyData',
                                    defaultMessage: '品种满足率'
                                })}</Col></Row>}>
                                {this.chartsContent(dvRate, scale, legendItems, arr, 'PI项数', '备货项数', '品种满足率')}
                            </DescriptionList>}
                        {conditions.type === partOrderList.金额满足率 &&
                            <DescriptionList size="large" title={<Row><Col span={12}>
                                {formatMessage({
                                    id: 'detailPanel.table.amountMeetData',
                                    defaultMessage: '金额满足率'
                                })}</Col></Row>}>
                                {this.chartsContent(dvRate, scale, legendItems, arr, 'PI金额', '备货金额', '金额满足率')}
                            </DescriptionList>}
                        {conditions.type === 3 &&
                            <DescriptionList size="large" title={<Row><Col span={12}>
                                {formatMessage({
                                    id: 'detailPanel.table.quantityData',
                                    defaultMessage: '数量满足率'
                                })}</Col></Row>}>
                                {this.chartsContent(dvRate, scale, legendItems, arr, 'PI数量', '备货数量', '数量满足率')}
                            </DescriptionList>}
                    </Card>
                </Spin>
            </div>
        );
    }
}

TablePanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    data: PropTypes.object.isRequired,
    hasError: PropTypes.string,
    intl: PropTypes.object,
    loading: PropTypes.bool,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getData = selectorFactory(['page', 'domainData', 'list', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const mapStateToProps = state => ({
    data: getData(state),
    loading: state.getIn(['page', 'domainData', 'list', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'list', 'hasError']),
    conditions: getConditions(state),
});
export default connect(mapStateToProps, null)(injectIntl(TablePanel));
